package net.cyan.commons.validate.validator;

import net.cyan.commons.validate.*;
import net.cyan.commons.util.Message;

import java.lang.reflect.Array;
import java.util.Collection;

/**
 * 
 * @author camel
 * @date 2008-12-21
 */
public class MaxCountValidator extends PropertyValidator
{
    public static final String MESSAGE = "cyan.validation.maxcount";

    private int value;

    public MaxCountValidator()
    {
    }

    public int getValue()
    {
        return value;
    }

    public void setValue(int value)
    {
        this.value = value;
    }

    protected boolean validate(Object value, Object bean) throws Exception
    {
        if (value == null)
            return false;
        if (value instanceof Collection)
            return ((Collection) value).size() <= this.value;
        return !value.getClass().isArray() || Array.getLength(value) <= this.value;
    }

    protected Object getMessage(Object value, Object bean, String property, String prefix, Validation validation)
            throws Exception
    {
        return new Message(MESSAGE, validation.getShowName(property, this.property, bean), this.value);
    }

    public String getValueString()
    {
        return Integer.toString(value);
    }
}
